package com.atguigu.chapter11.function;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/21 9:32
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        Table table = tEnv.fromDataStream(waterSensorStream);
        // 1. table API中使用
        // 1.1 使用内联方式  sum(vc)
    
        /*table
            .groupBy($("id"))
            .select($("id"), call(MySum.class, $("vc")).as("sum_vc"))
            .execute()
            .print();*/
        // 1.2 注册之后使用
        // 略
        
        // 2. 在sql中使用
        tEnv.createTemporaryView("t", table);
        tEnv.createTemporaryFunction("my_sum", MySum.class);
    
        tEnv.sqlQuery("select id, my_sum(vc) my_sum from t group by id").execute().print();
        
        
        
    }
    
    public static class MyAcc {
       public Integer sum = 0;
    }
    
    // 泛型一: 返回值类型  泛型二: 累加器 必须是可变
    public static class MySum extends AggregateFunction<Integer, MyAcc> {
        
        @Override
        public Integer getValue(MyAcc acc) {
            return acc.sum;
        }
        
        @Override
        public MyAcc createAccumulator() {
            return new MyAcc();
        }
        
        public void accumulate(MyAcc acc, Integer vc) {
            acc.sum += vc;
        }
        
    }
    
}


